<?php

App::uses('AppController', 'Controller');

/**
 * Wallets Controller
 *
 * @property Wallet $Wallet
 * @property PaginatorComponent $Paginator
 */
class WalletsController extends AppController
{

    /**
     * Components
     *
     * @var array
     */
    public $components = array('Paginator');

    public function beforeFilter()
    {
        parent::beforeFilter();
    }

    /**
     * index method
     *
     * @return void
     */
    public function index()
    {
        $this->Wallet->recursive = 0;
        $this->paginate = array('conditions' => array('User.id' => $this->Auth->user('id')));
        $this->set('wallets', $this->Paginator->paginate());
    }

    public function isAuthorized($user)
    {
        if (in_array($this->action, array('edit', 'delete')))
        {
            if ($user['id'] != $this->Auth->user('id'))
            {
                return false;
            }
        }
        return true;
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null)
    {
        if (!$this->Wallet->exists($id))
        {
            throw new NotFoundException(__('Invalid wallet'));
        }
        $options = array('conditions' => array('Wallet.' . $this->Wallet->primaryKey => $id));
        $wallet = $this->Wallet->find('first', $options);
        //debug($wallet);
        $this->set('wallet', $wallet);
    }

    /**
     * add method
     *
     * @return void
     */
    public function add()
    {
        $id_user = $this->Auth->user('id');

        if ($this->request->is('post'))
        {
            $data = $this->request->data;
            $numberWallet = $this->Wallet->find('count',array('conditions'=>array('user_id'=>$id_user)));
            if ($numberWallet < 5)
            {
                if($numberWallet == 0) {
                    $data['Wallet']['default'] = 1;
                }
                $this->Wallet->create();
                if ($this->Wallet->save($data))
                {
                    $this->Session->setFlash(__('The wallet has been saved.'), 'alert-success');
                    return $this->redirect(array('action' => 'index'));
                } else
                {
                    $this->Session->setFlash(__('The wallet could not be saved. Please, try again.'), 'alert-danger');
                }
            } else
            {
                $this->Session->setFlash(__('Could not create wallet maximun is 5.'), 'alert-danger');
            }
        }
        //Find UserID, UserName
        $condition = array('fields' => array('User.id', 'User.username'), 'conditions' => array('User.id' => $id_user));
        $users = $this->Wallet->User->find('all', $condition);
        $this->loadModel('Profile');
        $profile = $this->Profile->find('first', array('conditions' => array('users_id' => $id_user)));
        //debug($profile);
        $this->set(compact('users', 'profile'));
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null)
    {
        if (!$this->Wallet->exists($id))
        {
            throw new NotFoundException(__('Invalid wallet'));
        }
        if ($this->request->is(array('post', 'put')))
        {
            if ($this->Wallet->save($this->request->data))
            {
                $this->Session->setFlash(__('The wallet has been saved.'), 'alert-success');
                return $this->redirect(array('action' => 'index'));
            } else
            {
                $this->Session->setFlash(__('The wallet could not be saved. Please, try again.'), 'alert-danger');
            }
        } else
        {
            $options = array('conditions' => array('Wallet.' . $this->Wallet->primaryKey => $id));
            $this->request->data = $this->Wallet->find('first', $options);
        }
        $users = $this->Wallet->User->find('list', array('conditions' => array('User.id' => $this->Auth->user('id'))));
        debug($users);
        $this->set(compact('users'));
        $this->changemoney();
    }

    /**
     * Thay doi so tien
     * 
     */
    public function changemoney()
    {
        $id_user = $this->Auth->user('id');
        //check wallet >=2
        $number = $this->Wallet->find('count', array('conditions' => array('user_id' => $id_user), 'recursive' => 0));
        if ($number < 2)
        {
            $this->Session->setFlash("You have less than 2 wallets, Please create more wallet to change money!!", 'alert-danger');
            $this->redirect(array('action'=>'add'));
        } else
        {
            //get list wallet
            $sql = "SELECT id,current_money, name FROM tb_wallets WHERE user_id = {$id_user}";
            $wallets = $this->Wallet->query($sql);
            //convert data id wallet + curren money
            $current = array();
            foreach ($wallets as $item)
            {
                $current[$item['tb_wallets']['id']] = $item['tb_wallets']['current_money'];
            }

            $this->set('wallets', $wallets);

            if ($this->request->is('post'))
            {
                $data = $this->request->data;
                $wSend = $data['Wallet']['id1'];
                $wReceive = $data['Wallet']['id2'];

                $money = $data['Wallet']['money'];
                //debug($current[$wSend]);die;
                if ($money > $current[$wSend])
                {
                    $this->Session->setFlash('Money Send Biger Than Current Money', 'alert-danger');
                } else
                {
                    if ($wSend == $wReceive)
                    {
                        $this->Session->setFlash('Change money between two wallets must be different!', 'alert-danger');
                        $this->redirect(array('action' => 'changemoney'));
                    } else
                    {
                        //Update current money in 2 wallets
                        $mWSend = "UPDATE tb_wallets SET current_money = current_money - {$money}, spent = spent + {$money} WHERE id = {$wSend}";
                        $mReceiv = "UPDATE tb_wallets SET current_money = current_money + {$money}, earn = earn +{$money} WHERE id = {$wReceive}";
                        //Insert Transaction
                        date_default_timezone_set("Asia/Ho_Chi_Minh");
                        $date = date("Y-m-d H:i:s");
                        $this->Wallet->query($mWSend);
                        $this->Wallet->query($mReceiv);
                        $tWsend = "INSERT INTO tb_transactions(wallet_id, category_id, created, parent_id, money, with_who) VALUES ({$wSend},16,'{$date}',0, '{$money}', 'Me')";
                        $tWreceiv = "INSERT INTO tb_transactions(wallet_id, category_id, created, parent_id, money, with_who) VALUES ({$wReceive},17,'{$date}',0, '{$money}', 'Me')";
                        $this->Wallet->Transaction->query($tWsend);
                        $this->Wallet->Transaction->query($tWreceiv);

                        $this->Session->setFlash('Change money success!!', 'alert-success');
                        $this->redirect(array('action' => 'index'));
                    }
                }
            }
        }

        //debug($wallets); die;
    }

    /*
     * set wallet default method
     * @return void
     */

    public function setdefault()
    {
        $id_user = $this->Auth->user('id');
        //count wallet of user
        /*
         * if count = 0 -> create
         * else show form setdefault
         */
        $count = $this->Wallet->find('count', array('conditions' => array('user_id' => $id_user)));
        if ($count > 0)
        {
            $sql = "SELECT id, name FROM tb_wallets WHERE user_id = {$id_user}";
            $wallets = $this->Wallet->query($sql);
            $wallet = array();
            foreach ($wallets as $item)
            {
                $wallet[$item['tb_Wallets']['id']] = $item['tb_Wallets']['name'];
            }
            $this->set('wallet', $wallet);
            if ($this->request->is('post'))
            {
                $data = $this->request->data;
                $idWallet = $data['Wallet']['default'];
                $sql = "UPDATE tb_wallets SET tb_wallets.default = 0 WHERE user_id = {$id_user}";
                $this->Wallet->query($sql);
                $setdefault = "UPDATE tb_wallets SET tb_wallets.default = 1 WHERE id = {$idWallet}";
                $this->Wallet->query($setdefault);
                $this->Session->setFlash('Set default successfull!!', 'alert-success');
                $this->redirect(array('controller' => 'transactions', 'action' => 'index'));
            }
        } else
        {
            $this->Session->setFlash('You have not any wallet, Please create a new wallet!', 'alert-danger');
            $this->redirect(array("action" => 'add'));
        }

        //debug($wallet); die;
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function delete($id = null)
    {
        $this->Wallet->id = $id;
        if (!$this->Wallet->exists())
        {
            throw new NotFoundException(__('Invalid wallet'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Wallet->delete())
        {
            $this->Session->setFlash(__('The wallet has been deleted.'), 'alert-success');
        } else
        {
            $this->Session->setFlash(__('The wallet could not be deleted. Please, try again.'), 'alert-danger');
        }
        return $this->redirect(array('action' => 'index'));
    }

}
